﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ZFY.UnitOfWork;

namespace ZFY.EntityFrameworkCore
{
    public class EfCoreTransactionApi : ITransactionApi
    {
        public EfCoreTransactionApi(IDbContextTransaction dbContextTransaction,DbContext starterDbContext)
        {
            DbContextTransaction = dbContextTransaction;
            StarterDbContext = starterDbContext;
        }
        public DbContext StarterDbContext { get; }
        public IDbContextTransaction DbContextTransaction { get; }
        //相同dbcontext但connection不同。则放到这里处理事务
        public List<DbContext> AttendedDbContexts { get; }

        public async Task CommitAsync(CancellationToken cancellationToken)
        {
            foreach (var dbContext in AttendedDbContexts)
            {
                await dbContext.Database.CommitTransactionAsync(cancellationToken);
            }
            await DbContextTransaction.CommitAsync(cancellationToken);
        }

        public void Dispose()
        {
            DbContextTransaction.Dispose();
        }

        public async Task RollbackAsync(CancellationToken cancellationToken)
        {
            foreach (var dbContext in AttendedDbContexts)
            {
                await dbContext.Database.RollbackTransactionAsync(cancellationToken);
            }
            await DbContextTransaction.RollbackAsync(cancellationToken);
        }
    }
}
